<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" show-icon center> </el-alert>
      <el-steps :space="200" :active="parseInt(this.activeName)" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs tab-position="left" v-model="activeName" @tab-click="handleClick" :before-leave="leaveTag">
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息表格 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="goodsList" :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in goodsParamForm" :key="item.att_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="params" v-for="(params, index) in item.attr_vals" :key="index" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in goodsAbbrForm" :key="item.att_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload class="upload-demo" :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture" :on-success="uploadSuccess" :headers="headersObj">
              <el-button size="small" type="primary" @click="uploadPic">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myQuillEditor" v-model="addForm.goods_introduce" />
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="预览" :visible.sync="dialogVisible" width="50%">
      <el-image :src="src"></el-image>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Add',
  data() {
    return {
      activeName: '0',
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 10,
        goods_number: 10,
        goods_weight: 10,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字值' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { type: 'number', message: '重量必须为数字值' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字值' }
        ],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }]
      },
      goodsList: [],
      goodsAbbrForm: [],
      goodsParamForm: [],
      fileList: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      dialogVisible: false,
      src: ''
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    async getGoodsList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.goodsList = res.data
    },
    async getGoodsForm(type) {
      const { data: res } = await this.$http.get(`categories/${this.addForm.goods_cat[2]}/attributes`, { params: { sel: type } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      if (type == 'only') this.goodsAbbrForm = res.data

      if (type == 'many') {
        res.data.forEach(item => {
          if (item.attr_vals.length > 0) item.attr_vals = item.attr_vals.split(' ')
          else item.attr_vals = []
        })
        this.goodsParamForm = res.data
      }
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    leaveTag(activeName, oldActiveName) {
      if (oldActiveName == '0' && activeName !== '0' && this.addForm.goods_cat.length == 0) {
        this.$message.error('请先选择商品分类！')
        return false
      }
      return true
    },
    handleClick() {
      if (this.activeName == '1') {
        this.getGoodsForm('many')
      }
      if (this.activeName == '2') {
        this.getGoodsForm('only')
      }
    },
    handleRemove(file, fileList) {
      let index = this.addForm.pics.findIndex(item => item.pic == file.response.data.tmp_path)
      this.addForm.pics.splice(index, 1)
      console.log(file, this.addForm.pics)
    },
    handlePreview(file) {
      console.log(file)
      this.src = file.response.data.url
      this.dialogVisible = true
    },
    uploadSuccess(response, file, fileList) {
      if (response.meta.status !== 200) return
      this.addForm.pics.push({ pic: response.data.tmp_path })
      console.log(response, this.addForm.pics)
    },
    uploadPic() {
      // this.addForm.pics =
    },
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          this.addForm.goods_cat = this.addForm.goods_cat.join(',')
          this.goodsParamForm.forEach(item => {
            this.addForm.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            })
          })
          this.goodsAbbrForm.forEach(item => {
            this.addForm.attrs.push({
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            })
          })
          console.log(this.addForm, this.goodsParamForm, this.goodsAbbrForm)

          const { data: res } = await this.$http.post('goods', this.addForm)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.$router.push('/home/goods')
          console.log(res)
        } else return this.$message.error('请填写必要的表单项')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 10px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.el-image {
  width: 100%;
  height: 100%;
}
.quill-editor {
  margin-bottom: 15px;
}
</style>
